package com.weichai.app.page;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.weichai.app.App;
import com.weichai.app.R;
import com.weichai.app.arch.http.ApiException;
import com.weichai.app.arch.http.ApiExceptionVM;
import com.weichai.app.arch.utils.GpsUtil;
import com.weichai.app.page.main.MainModel;
import com.weichai.app.page.mine.UserCenterVM;

import java.util.List;

import dev.utils.app.BarUtils;
import dev.utils.app.permission.PermissionUtils;

import com.weichai.app.page.common.dialog.AlertDialog.AlertHint;

public class MainActivity extends AppCompatActivity implements GpsUtil.GPSInterface {
    private LocationClient mLocationClient;
    private MainModel mainModel;
    private GpsUtil gpsUtil;
    private com.weichai.app.page.common.dialog.AlertDialog alertDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BarUtils.transparentStatusBar(this);
        setContentView(R.layout.activity_main);
        mainModel = new ViewModelProvider(this).get(MainModel.class);
        // 默认北京市
        mainModel.locationCity.setValue("北京市");
        if (!PermissionUtils.isGranted(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION)) {
            PermissionUtils.permission(Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    .callback(new PermissionUtils.PermissionCallback() {
                        @Override
                        public void onGranted() {
                            if (GpsUtil.gpsIsOpen(getApplicationContext())) {
                                startLocation();
                            } else {
//                                showDialog();
                            }
                        }

                        @Override
                        public void onDenied(List<String> grantedList, List<String> deniedList,
                                             List<String> notFoundList) {

                        }
                    }).request(this);
        } else {
            if (GpsUtil.gpsIsOpen(this)) {
                startLocation();
            } else {
//                showDialog();
            }
        }

        gpsUtil = new GpsUtil(this);
        gpsUtil.setGPSInterface(this);
        requestPermission();

        initVM();
    }

    /**
     * 初始化VM
     */
    private void initVM() {
        UserCenterVM userCenterVM = new ViewModelProvider(App.getApp()).get(UserCenterVM.class);
        userCenterVM
                .loginOutData
                .observe(this, value -> {
                    Navigation.findNavController(MainActivity.this,
                            R.id.nav_host_fragment_content_main)
                            .navigate(R.id.main_to_login_page);
                });

        new ViewModelProvider(App.getApp())
                .get(ApiExceptionVM.class)
                .apiExceptionData
                .observe(this, apiException -> {
                    if (apiException.code.equals("401")) {
                        userCenterVM.loginOut("2");
                        if (alertDialog == null) {
                            alertDialog = new com.weichai.app.page.common.dialog.AlertDialog(MainActivity.this);
                            alertDialog.setOutSideDismiss(false);
                            alertDialog.setBackPressEnable(false);
                        }
                        if (!alertDialog.isShowing()) {
                            alertDialog.showAlert(new AlertHint("登录已失效，请重新登录", null));
                        }


                    }
                });
    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("请开启手机定位服务").setCancelable(false).setPositiveButton("确定", (dialog, which) -> {
            dialog.dismiss();
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }).setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 请求权限
     */
    private void requestPermission() {
        mainModel.recordAudioPermission.observe(this, requestPermission -> {
            if (requestPermission) {
                PermissionUtils.permission(Manifest.permission.RECORD_AUDIO)
                        .callback(new PermissionUtils.PermissionCallback() {
                            @Override
                            public void onGranted() {

                            }

                            @Override
                            public void onDenied(List<String> grantedList, List<String> deniedList,
                                                 List<String> notFoundList) {

                            }
                        }).request(this);
            }
        });

        mainModel.locationPermission.observe(this, locationPermission -> {
            if (locationPermission) {
                PermissionUtils.permission(Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION)
                        .callback(new PermissionUtils.PermissionCallback() {
                            @Override
                            public void onGranted() {
                                if (GpsUtil.gpsIsOpen(getApplicationContext())) {
                                    startLocation();
                                } else {
//                                    showDialog();
                                }
                            }

                            @Override
                            public void onDenied(List<String> grantedList, List<String> deniedList,
                                                 List<String> notFoundList) {

                            }
                        }).request(this);
            }
        });
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        if (null == mLocationClient) {
            mLocationClient = new LocationClient(getApplicationContext());
            LocationClientOption option = new LocationClientOption();
            option.setOpenGps(true);
            option.setCoorType("bd09ll");
            option.setIsNeedAddress(true);
            option.setScanSpan(1000);
            mLocationClient.setLocOption(option);
            MyLocationListener myLocationListener = new MyLocationListener();
            mLocationClient.registerLocationListener(myLocationListener);
        }
        mLocationClient.start();
        mLocationClient.requestLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != gpsUtil) {
            gpsUtil.onDestroy();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(this);
    }

    @Override
    public void gpsSwitchState(boolean gpsOpen) {
        if (gpsOpen) {
            startLocation();
        }
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }
            String city = location.getCity();
            Log.i("位置：", city);
            if (!TextUtils.isEmpty(city)) {
                mainModel.locationCity.setValue(city);
                mainModel.locationLatLng.setValue(new LatLng(location.getLatitude(), location.getLongitude()));
                if (null != mLocationClient) {
                    mLocationClient.stop();
                }
            }
        }
    }
}
